package com.genesis.yunnanji.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.genesis.yunnanji.R;
import com.genesis.yunnanji.config.GenesisApiConfig;
import com.jaeger.library.StatusBarUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.List;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by Administrator on 2018/2/28.
 */

public class StoreWeb extends BaseActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {

    private WebView mWebView;

    private ProgressBar mProgressBar;

    private SwipeRefreshLayout mSwipeRefreshLayout;
    private Toolbar mToolbar;

    private String url;

    private String id;

    private RelativeLayout share;
    private TextView mTitle;

    private ValueCallback<Uri[]> fileChooseCallback;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_storeweb);

    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        mTitle = (TextView) findViewById(R.id.tv_storeweb_title);
        share = (RelativeLayout) findViewById(R.id.bt_web_share);
        mWebView = (WebView) findViewById(R.id.wv_storeweb_webview);
        mProgressBar = (ProgressBar) findViewById(R.id.pb_storeweb_progress);
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.sr_storeweb_swipe);
        mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.main_color));
        mSwipeRefreshLayout.setEnabled(false);
        mToolbar = (Toolbar) findViewById(R.id.tb_storeweb_toolbar);
        mToolbar.setBackgroundColor(getResources().getColor(R.color.main_color));
        mToolbar.setTitle("");
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                    return;
                }
                finish();
            }
        });
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.main_color), 2);
        url = getIntent().getStringExtra("url");
        id = getIntent().getStringExtra("news_id");
    }

    @Override
    protected void setUpView() {
        Log.e("url", url);
        share.setOnClickListener(this);
        mWebView.loadUrl(url);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mProgressBar.setMax(100);
        setUpWebview();
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                    return;
                }
                finish();
            }
        });
    }


    private void setUpWebview() {
        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.setWebViewClient(new mWebClient());
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setAppCacheEnabled(false);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setBuiltInZoomControls(false);
        mWebView.getSettings().setDefaultFontSize(12);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setDatabaseEnabled(true);
        mWebView.getSettings().setGeolocationEnabled(true);
        mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
        if (Build.VERSION.SDK_INT >= 21) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.addJavascriptInterface(new JsInterface(), "callapp");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_web_share:
                UMImage thumb = new UMImage(context, R.mipmap.sharelog);
                String[] str = mWebView.getUrl().split("__apptoken__");
                String shareUrl = str[0];
                UMWeb web = new UMWeb(shareUrl);
                web.setTitle(mWebView.getTitle());//标题
                web.setThumb(thumb);
                web.setDescription(mWebView.getTitle());
                new ShareAction(StoreWeb.this)
                        .withMedia(web)
                        .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SMS, SHARE_MEDIA.WEIXIN_FAVORITE, SHARE_MEDIA.EMAIL)
                        .open();
                break;
        }
    }

    @Override
    public void onRefresh() {
        mWebView.loadUrl(mWebView.getUrl());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10001) {
            switch (resultCode) {
                case Activity.RESULT_OK:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    if (selectList == null || selectList.size() == 0) {
                        if (StoreWeb.this.fileChooseCallback != null)
                            StoreWeb.this.fileChooseCallback.onReceiveValue(null);
                        return;
                    }
                    String path = selectList.get(0).getCompressPath();
                    if (TextUtils.isEmpty(path))
                        path = selectList.get(0).getPath();
                    if (StoreWeb.this.fileChooseCallback != null) {
                        File imgFile = new File(path);
                        if(!imgFile.exists()){
                            Toast.makeText(StoreWeb.this, "文件不存在", Toast.LENGTH_SHORT).show();
                            StoreWeb.this.fileChooseCallback.onReceiveValue(null);
                            return;
                        }
                        Uri fileUri;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                            fileUri = FileProvider.getUriForFile(StoreWeb.this, "com.genesis.yunnanji.MyFileProvider", imgFile);
                        else
                            fileUri = Uri.fromFile(imgFile);
                        Uri[] uris = {fileUri};
                        StoreWeb.this.fileChooseCallback.onReceiveValue(uris);
                    }
                    break;
                default:
                    if (StoreWeb.this.fileChooseCallback != null)
                        StoreWeb.this.fileChooseCallback.onReceiveValue(null);
                    break;
            }
        }
    }

    private class MyWebChromeClient extends WebChromeClient {


        @Override
        public void onReceivedTitle(WebView view, String title) {
            // TODO Auto-generated method stub
//            mToolbar.setTitle(title);
            Log.e("title", title);
            mTitle.setText(title);

        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {

            if (newProgress == 100) {
                mProgressBar.setVisibility(View.GONE);
                mSwipeRefreshLayout.setRefreshing(false);

            } else {
                if (mProgressBar.getVisibility() == View.GONE) {
                    mProgressBar.setVisibility(View.VISIBLE);
                    mProgressBar.setProgress(newProgress);
                }
                if (!mSwipeRefreshLayout.isRefreshing()) {
                    mSwipeRefreshLayout.setRefreshing(true);
                }
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            StoreWeb.this.fileChooseCallback = filePathCallback;
            new File(StoreWeb.this.getCacheDir().getAbsolutePath() + "/images/").mkdirs();
            PictureSelector.create(StoreWeb.this)
                    .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
//                .theme(R.style.style_picture_white)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                    .maxSelectNum(1)// 最大图片选择数量 int
                    .minSelectNum(0)// 最小选择数量 int
                    .imageSpanCount(4)// 每行显示个数 int
                    .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .previewImage(true)// 是否可预览图片 true or false
                    .previewVideo(false)// 是否可预览视频 true or false
                    .enablePreviewAudio(false) // 是否可播放音频 true or false
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
//                .setOutputCameraPath(FileUtils.getAppDefPath(FileUtils.PATH_IMAGE))// 自定义拍照保存路径,可不填
                    .enableCrop(false)// 是否裁剪 true or false

                    // .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                    .withAspectRatio(1, 1)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                    // .hideBottomControls()// 是否显示uCrop工具栏，默认不显示 true or false
                    .isGif(true)// 是否显示gif图片 true or false
//                .compressSavePath(FileUtils.getAppDefPath(FileUtils.PATH_IMAGE))//压缩图片保存地址
                    .freeStyleCropEnabled(false)// 裁剪框是否可拖拽 true or false
                    .circleDimmedLayer(false)// 是否圆形裁剪 true or false
//                    .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
//                    .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    .compress(true)
                    .compressSavePath(StoreWeb.this.getCacheDir().getAbsolutePath() + "/images/")
                    .compress(true)// 是否压缩 true or false
                    .openClickSound(false)// 是否开启点击声音 true or false
                    // .selectionMedia()// 是否传入已选图片 List<LocalMedia> list
                    // .previewEggs()// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                    // .cropCompressQuality()// 裁剪压缩质量 默认90 int
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
//                     .cropWH(480, 800)// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
                    .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                    .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                    // .videoQuality()// 视频录制质量 0 or 1 int
                    //  .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
                    // .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
                    // .recordVideoSecond()//视频秒数录制 默认60s int
                    .forResult(10001);//结果回调onActivityResult code
            return true;//super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
        }

    }

    private class mWebClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("tel:")) {
                Intent intent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(url));
                startActivity(intent);
                return true;
            } else {
                if (Build.VERSION.SDK_INT < 26) {
                    view.loadUrl(url);
                    return true;
                }

            }
            return false;
        }


        @Override
        public void onPageFinished(WebView view, String url) {
            share.setVisibility(View.VISIBLE);
            super.onPageFinished(view, url);
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.e("keycode", keyCode + "");
        Log.e("cangoback", mWebView.canGoBack() + "");
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        } else {
            finish();
        }
        return false;
    }

    @Override
    public void onPause() {
        super.onPause();
        mWebView.pauseTimers();

    }

    @Override
    public void onResume() {
        super.onResume();
        mWebView.resumeTimers();
        mWebView.onResume();
    }

    @Override
    protected void onDestroy() {
        mWebView.destroy();
        mWebView = null;
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @SuppressLint("JavascriptInterface")
    final class JsInterface {
        public JsInterface() {
        }

        @JavascriptInterface
        public void Pay(String id) {

            Intent intent = new Intent(context, SelectPay.class);
            intent.putExtra("id", id);
            startActivity(intent);

        }

        @JavascriptInterface
        public void Login() {
            Intent intent = new Intent(context, Login.class);
            startActivity(intent);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEvent(String num) {
        Log.e("event", num);
        if (num.equals("login")) {
            Log.e("url", mWebView.getUrl() + GenesisApiConfig.FROM_APP + GenesisApiConfig.APP_TOKEN + genesisUtils.getAppToken());
            mWebView.loadUrl(mWebView.getUrl() + GenesisApiConfig.FROM_APP + GenesisApiConfig.APP_TOKEN + genesisUtils.getAppToken());
        } else {
            mWebView.loadUrl(GenesisApiConfig.HOST + "/Mall/Center/orders.html");
        }
    }
}
